package 归并;

import 其他.DataStructure.TreeNode;
import org.junit.Test;

import java.util.LinkedList;
import java.util.Queue;

/*
    做完题一定写入表格
*/
public class 字符串造二叉树_惊了_是前序不是归并_297 {
    @Test
    public void test() {
        TreeNode r = deserialize("1 2 3 -1 -1 4 5");
        System.out.println(serialize(r));
        System.out.println(1);
    }

    //层序造树
    Queue<Integer> que = new LinkedList<>();
    public TreeNode deserialize(String w) {
        if(w==""){
            return null;
        }
        String[] ss = w.split(" ");
        for (String s : ss) {
            que.add(Integer.valueOf(s));
        }
        //为何传入参数curNode？
        //因为再外面弹出poll传入递归参数,要不1左右下降后，23不知道自己是23,而且val可能同，要传TreeNode
        int curVal = que.poll();
        TreeNode root = new TreeNode(curVal);
        front(root);
        return root;
    }
    private void front(TreeNode cur) {
        //can("cur:"+cur.val);
        if(que.size()<2){
            if(que.size()==0){
                return;
            }else if(que.size()==1){
                cur.left = new TreeNode(que.poll());
                return;
            }
        }else {
            Integer poll1 = que.poll();
            TreeNode one = poll1 == -1 ? null : new TreeNode(poll1);
            Integer poll2 = que.poll();
            TreeNode two = poll2 == -1 ? null : new TreeNode(poll2);
            cur.left = one;
            cur.right = two;
            //-1造null，导致下轮参数null.
            if(one != null) {
                front(one);
            }
            if(two!=null) {
                front(two);
            }
        }
        return;
    }
    //普通层序遍历
    public String serialize(TreeNode root) {
        if(root==null){
            return "";
        }
        StringBuilder sb = new StringBuilder();
        Queue<TreeNode> que = new LinkedList<>();
        //层序题初始rot, 但不用pt，看图
        que.add(root);

        while(!que.isEmpty()) {
            //1234
            TreeNode poll = que.poll();
            sb.append(poll==null?"-1 ":(poll.val+" "));
            if(poll==null){
                continue;
            }
            //不要加if,因为null需要pt第一轮（因为我要还原嘛！）
            que.add(poll.left);
            que.add(poll.right);
        }

        sb.deleteCharAt(sb.length()-1);
        return sb.toString();
    }
}
